package com.vma.jifu.others;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.vma.jifu.bizModel.model.Message2User;
import com.vma.jifu.bizModel.model.SystemMessage;

/**
 * Created by chenzui on 2017/7/18.
 */
public class SystemMessageService {
    public Page<SystemMessage> qryList(Integer userId,Integer cPage,Integer pSize){
        Page<SystemMessage> page = SystemMessage.dao.paginate(cPage,pSize,
                "SELECT\n" +
                        "  sm.title,\n" +
                        "  sm.content,\n" +
                        "  sm.create_time,\n" +
                        "  m2u.id,\n" +
                        "  m2u.status",
                "FROM system_message sm, message_2_user m2u\n" +
                        "WHERE m2u.message_id = sm.id AND user_id = ?\n" +
                        "AND m2u.is_delete = 0 ORDER by sm.create_time DESC\n",
                userId);
        return page;
    }

    public SystemMessage getById(Integer id){
        SystemMessage smg =  SystemMessage.dao.findFirst("SELECT sm.* FROM message_2_user m2u,system_message sm\n" +
                "WHERE m2u.message_id = sm.id\n" +
                "AND m2u.id = ?",id);
        Message2User.dao.findById(id).setStatus("1").update();
        return smg;
    }

    public void update(Integer id){
        Message2User message2User = Message2User.dao.findById(id);
        message2User.setStatus(message2User.getStatus().equals("1") ? "0":"1").update();
    }

    public void delete(Integer id){
        Message2User message2User = Message2User.dao.findById(id);
        message2User.setIsDelete("1").update();
    }

    public Long qryUnReadMsg(Integer userId){
        Record record = Db.findFirst("SELECT count(1) un_read_num FROM message_2_user WHERE status = 0 AND  is_delete = 0 AND user_id = ?",userId);
        return record.getLong("un_read_num");
    }
}
